package com.aw.baselib.util.download;

import com.aw.baselib.util.AwLog;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadQueueSet;
import com.liulishuo.filedownloader.FileDownloader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hzw.
 */

public class AwFileDownloadUtil {

    private static final String TAG = "FileDownloadUtil";
    private static int totalCounts;
    private static int finalCounts;

    public static void startDownload(List<DownloadResBean> list, boolean serial) {
        FileDownloadQueueSet queueSet = getQueueSet();
        final List<BaseDownloadTask> tasks = new ArrayList<>();
        for(DownloadResBean temp : list) {
            BaseDownloadTask task = FileDownloader.getImpl().create(temp.getUrl());
            task.setPath(temp.getPath());
            tasks.add(task);

        }

        totalCounts += tasks.size();
        AwLog.d(TAG, "startDownload totalCounts: " + totalCounts);
        if (serial) {
            // 串行执行该任务队列
            queueSet.downloadSequentially(tasks);
            // 如果你的任务不是一个List，可以考虑使用下面的方式，可读性更强
            //      queueSet.downloadSequentially(
            //              FileDownloader.getImpl().create(url).setPath(...),
            //              FileDownloader.getImpl().create(url).addHeader(...,...),
            //              FileDownloader.getImpl().create(url).setPath(...)
            //      );
        } else {
            // 并行执行该任务队列
            queueSet.downloadTogether(tasks);
            // 如果你的任务不是一个List，可以考虑使用下面的方式，可读性更强
            //    queueSet.downloadTogether(
            //            FileDownloader.getImpl().create(url).setPath(...),
            //            FileDownloader.getImpl().create(url).setPath(...),
            //            FileDownloader.getImpl().create(url).setSyncCallback(true)
            //    );
        }
        queueSet.start();// 最后你需要主动调用start方法来启动该Queue
    }

    private static FileDownloadQueueSet getQueueSet() {
        FileDownloadQueueSet queueSet = new FileDownloadQueueSet(queueTarget);
//        queueSet.disableCallbackProgressTimes();// 由于是队列任务, 这里是我们假设了现在不需要每个任务都回调`FileDownloadListener#progress`, 我们只关系每个任务是否完成, 所以这里这样设置可以很有效的减少ipc.
        queueSet.setCallbackProgressMinInterval(1000);
        queueSet.setWifiRequired(false);
        queueSet.setAutoRetryTimes(1); // 所有任务在下载失败的时候都自动重试一次
        return queueSet;
    }

    public static void startDownload(List<DownloadResBean> list, boolean serial, FileDownloadListener listener) {
        FileDownloadQueueSet queueSet = getQueueSet(listener);
        final List<BaseDownloadTask> tasks = new ArrayList<>();
        for(DownloadResBean temp : list) {
            BaseDownloadTask task = FileDownloader.getImpl().create(temp.getUrl());
            task.setPath(temp.getPath());
            tasks.add(task);

        }

        totalCounts += tasks.size();
        AwLog.d(TAG, "startDownload totalCounts: " + totalCounts);
        if (serial) {
            // 串行执行该任务队列
            queueSet.downloadSequentially(tasks);
            // 如果你的任务不是一个List，可以考虑使用下面的方式，可读性更强
            //      queueSet.downloadSequentially(
            //              FileDownloader.getImpl().create(url).setPath(...),
            //              FileDownloader.getImpl().create(url).addHeader(...,...),
            //              FileDownloader.getImpl().create(url).setPath(...)
            //      );
        } else {
            // 并行执行该任务队列
            queueSet.downloadTogether(tasks);
            // 如果你的任务不是一个List，可以考虑使用下面的方式，可读性更强
            //    queueSet.downloadTogether(
            //            FileDownloader.getImpl().create(url).setPath(...),
            //            FileDownloader.getImpl().create(url).setPath(...),
            //            FileDownloader.getImpl().create(url).setSyncCallback(true)
            //    );
        }
        queueSet.start();// 最后你需要主动调用start方法来启动该Queue
    }


    private static FileDownloadQueueSet getQueueSet(FileDownloadListener listener) {
        FileDownloadQueueSet queueSet = new FileDownloadQueueSet(listener);
//        queueSet.disableCallbackProgressTimes();// 由于是队列任务, 这里是我们假设了现在不需要每个任务都回调`FileDownloadListener#progress`, 我们只关系每个任务是否完成, 所以这里这样设置可以很有效的减少ipc.
        queueSet.setCallbackProgressMinInterval(10000);
        queueSet.setWifiRequired(false);
        queueSet.setAutoRetryTimes(1); // 所有任务在下载失败的时候都自动重试一次
        return queueSet;
    }


    private  static final FileDownloadListener queueTarget = new FileDownloadListener() {
        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            AwLog.d(TAG, String.format("[pending] tag[%s] %d/%d", task.getTag(), soFarBytes, totalBytes));
        }

        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            AwLog.d(TAG, String.format("[connected] tag[%s] %s %B %d/%d", task.getTag(), etag, isContinue, soFarBytes, totalBytes));
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            AwLog.d(TAG, String.format("下载中[progress] tag[%s] %d/%d , 下载速度: %d", task.getTag(), soFarBytes, totalBytes, task.getSpeed()));
        }

        @Override
        protected void blockComplete(BaseDownloadTask task) {
            AwLog.d(TAG, String.format("[blockComplete] tag[%s]", task.getTag()));
        }

        @Override
        protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
            AwLog.d(TAG, String.format("[retry] tag[%s] %s %d %d",
                    task.getTag(), ex, retryingTimes, soFarBytes));
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            finalCounts++;
            AwLog.d(TAG, String.format("[completed] id[%d] oldFile[%B]",
                    task.getId(),
                    task.isReusedOldFile()));
            AwLog.d(TAG, String.format("---------------------------------- %s", task.getTag())  + " ," + String.format("%d/%d", finalCounts, totalCounts));
            AwLog.d(TAG, String.format("下载完成id:%d, DownloadId: %d, TAG: %s, 总下载量: %d/%d, 文件名:  %s, 路径path:  %s, 路径targetFilePath:  %s, 下载url: %s, 平均速度: %d", task.getId(),
                    task.getDownloadId(), task.getTag() ,
                    finalCounts, totalCounts, task.getFilename(), task.getPath(), task.getTargetFilePath(),
                    task.getUrl(), task.getSpeed()));
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            finalCounts++;
            AwLog.d(TAG, String.format("[paused] id[%d] %d/%d", task.getId(), soFarBytes, totalBytes));
            AwLog.d(TAG, String.format("############################## %s", task.getTag()) + " ," + String.format("%d/%d", finalCounts, totalCounts));
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            finalCounts++;
            AwLog.d(TAG, e.getMessage() + " ," + String.format("%d/%d", finalCounts, totalCounts));
            AwLog.d(TAG, String.format("下载完成出错id:%d, DownloadId: %d, TAG: %s, 总下载量: %d/%d, 文件名:  %s, 路径path:  %s, 路径targetFilePath:  %s, 下载url: %s", task.getId(),
                    task.getDownloadId(), task.getTag() ,
                    finalCounts, totalCounts, task.getFilename(), task.getPath(), task.getTargetFilePath(),
                    task.getUrl()));
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            finalCounts++;
            AwLog.d(TAG, String.format("[warn] id[%d]", task.getId()));
            AwLog.d(TAG, String.format("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ %s", task.getTag()) + " ," + String.format("%d/%d", finalCounts, totalCounts));
        }
    };
}
